package org.zdp.demo.config.okhttp.interceptor;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.Buffer;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Slf4j
public class NetworkInterceptor implements Interceptor {

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        long start = System.currentTimeMillis();
        Response response = null;
        String requestBody = "";
        String requestHeader = "";
        String responseBody = "";
        String responseCode = "";
        String url = "";

        try {
            Request request = chain.request();
            url = request.url().toString();
            requestHeader = JSONUtil.toJsonStr(request.headers());
            requestBody = getRequestBody(request);
            log.info("开始请求:[{}]", url);
            response = chain.proceed(request);
            responseBody = response.body().string();
            responseCode = String.valueOf(response.code());
            MediaType mediaType = response.body().contentType();
            response = response.newBuilder().body(ResponseBody.create(mediaType, responseBody)).build();
        } catch (IOException e) {
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            String duration = String.valueOf(end - start);

            log.info("url: {} [{}]ms, header: {}, params: [{}], responseCode: [{}], result: [{}]",
                    url, duration, requestHeader, requestBody, responseCode, responseBody);
        }
        return response;
    }

    private String getRequestBody(Request request) {
        String requestContent = "";
        if (request == null) {
            return requestContent;
        }
        RequestBody requestBody = request.body();
        if (requestBody == null) {
            return requestContent;
        }

        Buffer buffer = null;
        try {
            buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = StandardCharsets.UTF_8;
            requestContent = buffer.readString(charset);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != buffer) {
                buffer.clear();
                buffer.close();
            }
        }
        return requestContent;
    }
}
